window.addEventListener('load', function () {
  var focus = this.document.querySelector('.focus');
  var ul = focus.children[0];
  var ol = focus.children[1];
  var w = focus.offsetWidth;
  var index = 0;
  // 自动播放无缝滚动
  var timer = setInterval(() => {
    index++;
    var left = - index * w;
    ul.style.transition = "all .3s";
    ul.style.transform = "translateX(" + left +"px)";
  }, 2000);
  // 监听过渡完成事件transitionend
  ul.addEventListener('transitionend', function () {
    if(index >= 3){
      index = 0;
      ul.style.transition = 'none';
      var left = - index * w;
      ul.style.transform = "translateX(" + left + "px)";
    }else if(index < 0){
      index = 2;
      ul.style.transition = 'none';
      var left = - index * w;
      ul.style.transform = "translateX(" + left + "px)";
    }
    // 小圆点跟随变化
    ol.querySelector('li.current').classList.remove('current');
    ol.children[index].classList.add('current');
  });
  // 手指滑动轮播图
  // 触摸拿到手指初始坐标
  var startX = 0;
  ul.addEventListener('touchstart', function (e) {
    startX = e.targetTouches[0].pageX;
    clearInterval(timer);
  });
  // 移动距离
  var moveX = 0;
  var flag = false;
  ul.addEventListener('touchmove', function (e) {
    moveX = e.targetTouches[0].pageX - startX;
    var left = - index * w + moveX;
    ul.style.transform = "translateX("+left+"px)";
    ul.style.transition = "none";
    flag = true;
    //阻止滚动屏幕的默认行为
    e.preventDefault;
  });
  // touchend 
  ul.addEventListener('touchend', function (e) {
    if(flag){
      if(Math.abs(moveX) > 50){
        // 右滑，上一张
        if(moveX > 0){
          index--;
        // 左滑，下一张
        }else{
          index++;
        }
        var left = - index * w;
        ul.style.transform = "translateX("+left+"px)";
        ul.style.transition = "all .3s";
      }else {
        // 回弹
        var left = - index * w;
        ul.style.transform = "translateX("+left+"px)";
        ul.style.transition = "all .1s";
      }
    }
    clearInterval(timer);
    var timer = setInterval(() => {
      index++;
      var left = - index * w;
      ul.style.transition = "all .3s";
      ul.style.transform = "translateX(" + left +"px)";
    }, 2000);
  });

    // 返回顶部模块制作
    var goBack = document.querySelector('.goBack');
    var nav = document.querySelector('nav');
    window.addEventListener('scroll', function () {
      //pageYoffset是被卷去的头部，offsetTop是离顶部的距离
      if(window.pageYOffset >= nav.offsetTop){
        goBack.style.display = 'block';
      }else{
        goBack.style.display = 'none';
      }
    });
    goBack.addEventListener('click', function () {
      window.scroll(0, 0);
    })
})